    //
    //  XOShopHomeViewController.m
    //  didigo
    //
    //  Created by JS_Coder on 2019/2/20.
    //  Copyright © 2019 lifayu. All rights reserved.
    //

#import "XOShopHomeViewController.h"
#import "XOShopViewModel.h"
#import "XOShopModel.h"
#import "EJSGoodsCategoryRequest.h"
#import "EJSGoodsListRequest.h"
#import "EJSCategoryTableViewCell.h"
#import "XOCategorySingleTableViewCell.h"
#import "XOCategoryWithImageCell.h"
#import "XOCategoryImageCellheader.h"
#import "EJSGoodsListViewController.h"
#import "XOCartViewController.h"
#import <UIView+BlocksKit.h>
#import "EJSSearchViewController.h"

@interface XOShopHomeViewController()<UITableViewDelegate,UITableViewDataSource, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout>{
    NSString * _categoryIdentifier;
    NSString * _categorySingleIdentifier;
    NSString * _categoryImageCellIdentifier;
    NSString * _categoryImageHeaderIdentifier;
    BOOL _isNew;
}

StrongProperty UITableView *defaultTableView; // 商铺分类使用一级时使用
StrongProperty UITableView *tableView;
StrongProperty UICollectionView *collectionView;
StrongProperty NSMutableArray *categoryList;
StrongProperty EJSCategoryModel *selectedCategory;
StrongProperty UIView *topSearchView;

@end

@implementation XOShopHomeViewController

#pragma mark - 生命周期
- (void)viewDidLoad {
    [super viewDidLoad];
    [self getGoodsCategoryList];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    XOShopModel *model = [XOShopViewModel shared].shopModel;
    self.shopModel = model;
    self.navigationItem.title = model.shopName;
    [self reloadData];
}

#pragma mark - 懒加载 和 Setter
- (void)setCategoryList:(NSMutableArray *)categoryList {
    if (_categoryList != categoryList) {
        _categoryList = categoryList;
        [self.tableView reloadData];
    }
}

- (void)setSelectedCategory:(EJSCategoryModel *)selectedCategory {
    if (_selectedCategory != selectedCategory) {
        _selectedCategory = selectedCategory;
        [self.collectionView reloadData];
    }
}

#pragma mark - 初始化UI
- (void)configOwnViews {
    _isNew = false;
    _categoryIdentifier = @"categoryTableIdentifier";
    _categorySingleIdentifier = @"_categorySingleIdentifier";
    _categoryImageCellIdentifier = @"_categoryImageCellIdentifier";
    _categoryImageHeaderIdentifier = @"_categoryImageHeaderIdentifier";
    [self configNavigationLeftItemWithImage:[UIImage imageNamed:@"back_icon"]];
//    [self configNavigationRightItemWithImage:[UIImage imageNamed:@"tabBarItem3_normal"]];

    [self.view addSubview:self.defaultTableView];
    [self.view addSubview:self.tableView];
    [self.view addSubview:self.collectionView];
    [self.view addSubview:self.topSearchView];
    
    FlyWeakSelf
    [self.topSearchView bk_whenTapped:^{
        EJSSearchViewController *searchVC = [[EJSSearchViewController alloc] init];
        XOShopModel *model = [XOShopViewModel shared].shopModel;
        searchVC.shopId = model.shopId;
        [weakSelf.navigationController pushViewController:searchVC animated:YES];
    }];
}

- (void)leftBarButtonAction:(id)sender {
    [self.tabBarController.navigationController popViewControllerAnimated:YES];
}

//- (void)rightBarButtonAction:(id)sender {
//    UIStoryboard *storyBoard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
//    XOCartViewController *cartVc = [storyBoard instantiateViewControllerWithIdentifier:@"XOCartViewController"];
//    [self.navigationController pushViewController:cartVc animated:YES];
//}

#pragma mark - 更新数据
- (void)reloadData {
    if (self.categoryList && self.categoryList.count > 0) {
        [self hideNoDataView];
    }else {
        [self showNoDataViewWithText:@"暂无商品~"];
        return;
    }
    
    if ([self.shopModel.classLevel intValue] <= 1) {
        self.defaultTableView.hidden = NO;
        self.tableView.hidden = YES;
        self.collectionView.hidden = YES;
        [self.defaultTableView reloadData];
    }else {
        self.defaultTableView.hidden = YES;
        self.tableView.hidden = NO;
        self.collectionView.hidden = NO;
        [self.tableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] animated:NO scrollPosition:UITableViewScrollPositionTop];
        self.selectedCategory = self.categoryList.firstObject;
    }
}

#pragma mark - 获取店铺商品分类
- (void)getGoodsCategoryList{
    XOShopModel *model = [XOShopViewModel shared].shopModel;
    EJSGoodsCategoryRequest *req = [EJSGoodsCategoryRequest new];
    req.shopId = model.shopId;
    req.type = @"children";
    FlyWeakSelf
    [req asyncRequestWithsuccessHandler:^(BaseResponse *response) {
        weakSelf.categoryList = [NSMutableArray arrayWithArray:response.data];
        [weakSelf reloadData];
    } failHandler:^(BaseResponse *response) {
        [[HUDHelper sharedInstance]tipMessage:response.message];
    }];
}

#pragma mark - UITableViewDelegate UITableViewDatasource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.categoryList.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    EJSCategoryModel *model = self.categoryList[indexPath.row];

    if ([tableView isEqual:self.defaultTableView]) {
        XOCategorySingleTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:_categorySingleIdentifier];
        [cell reloadDataWithCategory:model];
        return cell;
    }else {
        EJSCategoryTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:_categoryIdentifier forIndexPath:indexPath];
        cell.categoryNameLabel.text = model.categoryName;
        return cell;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    EJSCategoryModel *categoryModel = self.categoryList[indexPath.row];
    
    if ([self.shopModel.classLevel intValue] <= 1) {
        [tableView deselectRowAtIndexPath:indexPath animated:YES];
        EJSGoodsListViewController *goodsVc = [[EJSGoodsListViewController alloc]init];
        goodsVc.singleCategoryModel = categoryModel;
        [self.navigationController pushViewController:goodsVc animated:YES];
    }else {
        self.selectedCategory = categoryModel;
    }
}

#pragma mark - UICollectionViewDataSource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    if (self.shopModel.classLevel.intValue == 2) {
        return 1;
    }else {
        return self.selectedCategory.sons.count;
    }
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    if (self.shopModel.classLevel.intValue == 2) {
        return self.selectedCategory.sons.count;
    }else {
        EJSCategoryModel* secondModel = self.selectedCategory.sons[section];
        return secondModel.sons.count;
    }
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    XOCategoryWithImageCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:_categoryImageCellIdentifier forIndexPath:indexPath];
    
    if (self.shopModel.classLevel.intValue == 2) {
        EJSCategoryModel *secondModel = self.selectedCategory.sons[indexPath.row];
        [cell.categoryImageView setImageWithUrl:secondModel.categoryCover];
        cell.categoryNameLabel.text = secondModel.categoryName;
    }else {
        EJSCategoryModel *secondModel = self.selectedCategory.sons[indexPath.section];
        EJSCategoryModel *tirdModel = secondModel.sons[indexPath.row];
        [cell.categoryImageView setImageWithUrl: tirdModel.categoryCover];
        cell.categoryNameLabel.text = tirdModel.categoryName;
    }
    
    return cell;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    XOCategoryImageCellheader *header = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:_categoryImageHeaderIdentifier forIndexPath:indexPath];
    if (self.shopModel.classLevel.intValue == 2) {
        header.titleLabel.text = nil;
    }else {
        EJSCategoryModel *model = self.selectedCategory.sons[indexPath.section];
        header.titleLabel.text = model.categoryName;
    }
    return header;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
    if (self.shopModel.classLevel.intValue == 2) {
        return CGSizeZero;
    }else {
        return CGSizeMake(ScreenWidth * 0.7, 35);
    }
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if (self.shopModel.classLevel.intValue == 2) {
        EJSCategoryModel *model = self.selectedCategory.sons[indexPath.row];
        EJSGoodsListViewController *goodsVc = [[EJSGoodsListViewController alloc]init];
        goodsVc.categoryModel = self.selectedCategory;
        goodsVc.selectCategoryIndex = indexPath.row;
        goodsVc.selectCategoryModel = model;
        [self.navigationController pushViewController:goodsVc animated:YES];
    }else {
        EJSCategoryModel *model = self.selectedCategory.sons[indexPath.section];
        EJSGoodsListViewController *goodsVc = [[EJSGoodsListViewController alloc]init];
        goodsVc.categoryModel = model;
        goodsVc.selectCategoryIndex = indexPath.row;
        goodsVc.selectCategoryModel = [model.sons objectAtIndex:indexPath.row];
        [self.navigationController pushViewController:goodsVc animated:YES];
    }
}

#pragma mark - lazy

#pragma mark - CollectionView
- (UICollectionView *)collectionView {
    if (_collectionView != NULL) {
        return _collectionView;
    }
    CGFloat width = ScreenWidth * 0.7;
    CGFloat x = ScreenWidth * 0.3;
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc]init];

    { // 初始化FlowLayout
        int cols = 3;
        CGFloat itemWidth = (width - (cols + 3) * CommonMargin) / cols;
        CGFloat itemHeight = itemWidth * 3 / 2;
        flowLayout.itemSize = CGSizeMake(itemWidth, itemHeight);
        flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
        flowLayout.minimumLineSpacing = CommonMargin;
        flowLayout.minimumInteritemSpacing = CommonMargin;
        flowLayout.headerReferenceSize = CGSizeMake(ScreenWidth * 0.7, 35);
    }

    _collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(x, 66, width, self.view.height - NavigationBarHeight - TabBarHeight - StatusBarHeight-66) collectionViewLayout:flowLayout];

    { // 初始化CollectionView
        [_collectionView registerNib:[UINib nibWithNibName:@"XOCategoryWithImageCell" bundle:nil] forCellWithReuseIdentifier:_categoryImageCellIdentifier];
        [_collectionView registerNib:[UINib nibWithNibName:@"XOCategoryImageCellheader" bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:_categoryImageHeaderIdentifier];

        _collectionView.contentInset = UIEdgeInsetsMake(CommonMargin, CommonMargin, 0, CommonMargin);
        _collectionView.backgroundColor = UIColor.whiteColor;
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.alwaysBounceVertical = YES;
    }
    return _collectionView;
}

#pragma mark - TableView
- (UITableView *)defaultTableView {
    if (_defaultTableView != NULL) {
        return _defaultTableView;
    }
    _defaultTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 66, ScreenWidth, self.view.height - NavigationBarHeight - TabBarHeight-66) style:UITableViewStylePlain];
    _defaultTableView.separatorInset = UIEdgeInsetsMake(0, 70, 0, 15);
    [_defaultTableView registerNib:[UINib nibWithNibName:@"XOCategorySingleTableViewCell"bundle:nil] forCellReuseIdentifier: _categorySingleIdentifier];
    _defaultTableView.rowHeight = 44;
    _defaultTableView.delegate = self;
    _defaultTableView.dataSource = self;
    _defaultTableView.tableFooterView = [UIView new];
    return _defaultTableView;
}

- (UITableView *)tableView {
    if (_tableView != NULL) {
        return _tableView;
    }
    _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 66, ScreenWidth * 0.3, self.view.height - NavigationBarHeight - TabBarHeight-66) style:UITableViewStylePlain];
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [_tableView registerNib:[UINib nibWithNibName:@"EJSCategoryTableViewCell"bundle:nil] forCellReuseIdentifier: _categoryIdentifier];
    _tableView.rowHeight = 44;
    _tableView.delegate = self;
    _tableView.dataSource = self;
    return _tableView;
}

#pragma mark - topSearchView
- (UIView *)topSearchView {
    if (!_topSearchView) {
        _topSearchView = [[UIView alloc]initWithFrame:CGRectMake(15, 15, ScreenWidth - 30, 36)];
        _topSearchView.layer.cornerRadius = 18;
        _topSearchView.layer.masksToBounds = true;
        _topSearchView.layer.borderWidth = 0.5;
        _topSearchView.layer.borderColor = UIColorFromRGB(0xF0F0F0).CGColor;
        _topSearchView.backgroundColor = UIColorFromRGB(0xF0F0F0);
        
        UIImageView *searchImage = [[UIImageView alloc]initWithFrame:CGRectMake(15, (_topSearchView.frame.size.height - 15) / 2, 15, 15)];
        searchImage.image = [UIImage imageNamed:@"search"];
        [_topSearchView addSubview:searchImage];

        UILabel *placeHolder = [[UILabel alloc]init];
        placeHolder.text = NSLocalizedString(@"搜索商品名称", nil);
        [placeHolder sizeToFit];
        placeHolder.font = [UIFont systemFontOfSize:15];
        [placeHolder setCenterX: placeHolder.frame.size.width / 2 + CGRectGetMaxX(searchImage.frame)];
        [placeHolder setCenterY:_topSearchView.height/2.0];
        placeHolder.textAlignment = NSTextAlignmentCenter;
        placeHolder.textColor = UIColor.lightGrayColor;
        [_topSearchView addSubview:placeHolder];
    }
    return _topSearchView;
}


@end
